﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace YunShop_WebAPI.BLL
{
    public class BusinessCommon
    {
        /// <summary>
        /// 商品分类列表
        /// </summary>
        public static DataTable GetGoodClassData(int mCorpID,int mPtCorpID, string connstr)
        {
            string msql = @"SELECT FItemID, FName, FIcon, FParentID FROM  dbo.t_GoodsClass "
                    + "where (FCorpID = @mCorpID or (FCorpID = @mParentID and @mParentID > 0)) and FDeleted  > 0";
            SqlParameterList par_list = new SqlParameterList();
            par_list.Add("@mParentID", SqlDbType.Int, mPtCorpID);
            par_list.Add("@mCorpID", SqlDbType.BigInt, mCorpID);
            DataTable dt  = DBHelper.GetDataTable(msql, par_list.Get_List(), connstr);
            return dt;
        }

        /// <summary>
        /// 商品分类列表
        /// </summary>
        public static ArrayList GetGoodClassList(string shop_appid)
        {            
            int mCorpID = SystemInfo.GetSystemAppID(shop_appid, SystemAppID.CorpID);
            int mPtCorpID = SystemInfo.GetSystemAppID(shop_appid, SystemAppID.TopCorpID);
            string connstr = SystemInfo.GetClusterConn(shop_appid);
            DataTable dt = GetGoodClassData(mCorpID, mPtCorpID, SystemInfo.GetClusterConn(shop_appid));
            string str_filer = "FParentID = 0";
            DataRow[] drs_top = dt.Select(str_filer);            
            if (drs_top.Length == 0) return null;
            
            DataTable dt_top = drs_top.CopyToDataTable();
            ArrayList list_top = DBHelper.DataTable2ArrayList(dt_top);
            ArrayList datalist = new ArrayList();
            foreach (Hashtable row in list_top)
            {
                str_filer = string.Format("FParentID = {0}", CommonFun.ConvertToBigInt(row["FItemID"]));
                DataRow[] drs_children = dt.Select(str_filer);
                ArrayList list_children = new ArrayList();
                if (drs_children.Length > 0)
                {
                    DataTable dt_children = drs_children.CopyToDataTable();
                    list_children = DBHelper.DataTable2ArrayList(dt_children);
                }
                row["children"] = list_children;
                datalist.Add(row);
            }

            return datalist;
        }

        /// <summary>
        /// 商品列表
        /// </summary>
        public static ArrayList GetGoodsList(string shop_appid, string name, Int64 class_id,
            int page_index, int page_size,out int page_count)
        {
            page_count = 0;
            int mCorpID = SystemInfo.GetSystemAppID(shop_appid, SystemAppID.CorpID);
            Int64 mTopCorpID = SystemInfo.GetSystemAppID(shop_appid, SystemAppID.TopCorpID);
            Int64 mUserID = SystemInfo.GetSystemAppID(shop_appid, SystemAppID.UserID);
            string connstr = SystemInfo.GetClusterConn(shop_appid);
            string msql = @"EXEC pr_wap_dh_GetGoodsList @mPageSize,@mPageIndex,@mCorpID,@mTopCorpID,@mUserID,@mClassID,@mNumber,0";
            SqlParameterList par_list = new SqlParameterList();
            par_list.Add("@mPageSize", SqlDbType.Int, page_size);
            par_list.Add("@mPageIndex", SqlDbType.Int, page_index);
            par_list.Add("@mCorpID", SqlDbType.BigInt, mCorpID);
            par_list.Add("@mTopCorpID", SqlDbType.BigInt, mTopCorpID);
            par_list.Add("@mUserID", SqlDbType.BigInt, mUserID);
            par_list.Add("@mClassID", SqlDbType.BigInt, class_id);            
            par_list.Add("@mNumber", SqlDbType.VarChar, name);
            ArrayList datalist = DBHelper.Select(msql, par_list.Get_List(), connstr);
            if (datalist != null && datalist.Count > 0)
            {
                Hashtable ht = datalist[0] as Hashtable;
                page_count = Utils.GetPageCount(CommonFun.ConvertToInt(ht["FRowCount"]), page_size);
            }
            return datalist;
        }

        /// <summary>
        /// 购物车
        /// </summary>
        public static ArrayList GetShoppingCart(string shop_appid)
        {            
            Int64 mUserID = SystemInfo.GetSystemAppID(shop_appid, SystemAppID.UserID);
            int mCorpID = SystemInfo.GetSystemAppID(shop_appid, SystemAppID.CorpID);
            string connstr = SystemInfo.GetClusterConn(shop_appid); 

            string msql = @"SELECT b.FItemID, b.FName, b.FCode, b.FSpec, b.FUnitName, b.FSelPrice AS FPrice, "
                +"a.FQty, c.FGoodImg FROM dbo.t_UserShopping AS a INNER JOIN "
                +"dbo.t_Goods AS b ON a.FGoodsID = b.FItemID INNER JOIN "
                +"dbo.t_GoodsDetail AS c ON b.FItemID = c.FItemID "
                + "where a.FUserID = @mUserID and a.FQty > 0";
            SqlParameterList par_list = new SqlParameterList();
            par_list.Add("@mUserID", SqlDbType.BigInt, mUserID);
            ArrayList datalist = DBHelper.Select(msql, par_list.Get_List(), connstr);
            return datalist;
        }

        /// <summary>
        /// 商品详情
        /// </summary>
        public static Hashtable GetGoodsDetail(string shop_appid, Int64 goods_id)
        {            
            int mCorpID = SystemInfo.GetSystemAppID(shop_appid, SystemAppID.CorpID);            
            Int64 mUserID = SystemInfo.GetSystemAppID(shop_appid, SystemAppID.UserID);
            string connstr = SystemInfo.GetClusterConn(shop_appid);
            string msql = @"EXEC pr_wap_dh_GetGoodsDetail @mCorpID,@mUserID,@mGoodsID";
            SqlParameterList par_list = new SqlParameterList();
            par_list.Add("@mCorpID", SqlDbType.BigInt, mCorpID);            
            par_list.Add("@mUserID", SqlDbType.BigInt, mUserID);
            par_list.Add("@mGoodsID", SqlDbType.BigInt, goods_id);
            ArrayList datalist = DBHelper.Select(msql, par_list.Get_List(),connstr);
            Hashtable ht_result = new Hashtable();
            if (datalist != null && datalist.Count > 0)
            {
                ht_result = datalist[0] as Hashtable;
                var itemUrl = CommonFun.ConvertToString(ht_result["FProImage"]);
                ArrayList list_img = new ArrayList();
                if (!string.IsNullOrWhiteSpace(itemUrl))
                {                    
                    var arr = itemUrl.Replace("$$", "$").Split('$');
                    foreach (var str in arr)
                    {
                        if (!string.IsNullOrWhiteSpace(str))
                        {
                            Hashtable ht_img = new Hashtable();
                            ht_img["FGoodImg"] = str;
                            list_img.Add(ht_img);
                        }
                    }
                }
                ht_result["FProImage"] = list_img;
            }
            return ht_result;
        }
          
        /// <summary>
        /// 放入购物车
        /// </summary>
        public bool SetShoppingCart(string shop_appid, Int64 goods_id, decimal qty)
        {
            int mCorpID = SystemInfo.GetSystemAppID(shop_appid, SystemAppID.CorpID);
            Int64 mUserID = SystemInfo.GetSystemAppID(shop_appid, SystemAppID.UserID);
            string connstr = SystemInfo.GetClusterConn(shop_appid);
            string msql = @"if exists(Select FUserID From t_UserShopping where FUserID = @mUserID and FGoodsID = @mGoodsID)
                begin
	                Update t_UserShopping set FQty = @mQty 
                    where FUserID = @mUserID and FGoodsID = @mGoodsID
                end else begin
	                Insert into t_UserShopping(FUserID,FGoodsID,FQty)values(@mUserID,@mGoodsID,@mQty)
                end Delete t_UserShopping where FUserID = @mUserID and FGoodsID = @mGoodsID and FQty <= 0";
            SqlParameterList par_list = new SqlParameterList();
            par_list.Add("@mGoodsID", SqlDbType.BigInt, goods_id);
            par_list.Add("@mUserID", SqlDbType.BigInt, mUserID);
            par_list.Add("@mQty", SqlDbType.Decimal, qty);
            string mstr = DBHelper.ExeSQL(msql, par_list.Get_List(),connstr);
            return true;
        }

        /// <summary>
        /// 删除购物车商品
        /// </summary>
        public int DelShoppingCart(string shop_appid, ArrayList detailed, ref string msg)
        {
            int mCorpID = SystemInfo.GetSystemAppID(shop_appid, SystemAppID.CorpID);
            Int64 mUserID = SystemInfo.GetSystemAppID(shop_appid, SystemAppID.UserID);
            string connstr = SystemInfo.GetClusterConn(shop_appid);
            string msql = @"Delete t_UserShopping where FUserID = @mUserID and FGoodsID = @FGoodsID";
            SqlConnection con = new SqlConnection(connstr);
            con.Open();
            SqlTransaction tran = con.BeginTransaction();
            try
            {
                foreach (Hashtable row in detailed)
                {
                    row["mUserID"] = mUserID;
                    SqlCommand cmd = new SqlCommand(msql, con);
                    cmd.Connection = con;
                    cmd.Transaction = tran;
                    cmd.Parameters.Clear();
                    if (row != null) DBHelper.SetArgs(msql, row, cmd);
                    cmd.ExecuteNonQuery();
                }
                tran.Commit();
                msg = "删除成功";
            }
            catch (SqlException ex)
            {
                tran.Rollback();
                msg = ex.Message.Replace("\r\n", "");
                return 0;
            }
            finally
            {
                con.Close();
                con = null;
            }
            return 1;
        }

        public static Int64 GetParentStockID(int mCorpID,Int64 sStockID) {
            string connstr = SystemInfo.GetClusterConn(mCorpID);
            string msql = string.Format("select FStockID FROM t_Corpration where FItemID = {0}",mCorpID);
            Int64 mStockID = CommonFun.ConvertToBigInt(DBHelper.GetValue(msql, connstr));
            if (mStockID == 0) mStockID = sStockID;
            return mStockID;
        }

        /// <summary>
        /// 添加普通商品订单
        /// </summary>
        public static Hashtable AddOrderPay(string shop_appid, decimal mAmount, int mPayType, string remark,
            ArrayList detailed, ref int mResult, ref string msg)
        {
            if (detailed == null) return null;
            Int64 mStockID = SystemInfo.GetSystemAppID(shop_appid, SystemAppID.StockID); 
            int mCorpID = SystemInfo.GetSystemAppID(shop_appid, SystemAppID.TopCorpID);
            Hashtable ht_master = new Hashtable();
            ht_master["KInterID"] = 0;
            ht_master["FBillNo"] = "";
            ht_master["FSystemAppID"] = shop_appid;
            ht_master["FRStockID"] = mStockID;
            ht_master["FStockID"] = GetParentStockID(mCorpID, mStockID); 
            ht_master["FDataType"] = 10; 
            ht_master["FPlatformID"] = 1; //平台类型，0是ERP后台，1是小程序订货平台
            ht_master["FDate"] = System.DateTime.Now.ToString("yyyy-MM-dd");
            ht_master["FRemark"] = remark;
            ArrayList arrayList = new ArrayList();     

            foreach (Hashtable row in detailed)
            {
                Hashtable ht_detail = new Hashtable();
                ht_detail["mFInterID"] = 0;
                ht_detail["mFRowNo"] = 0;
                ht_detail["mFItemID"] = CommonFun.ConvertToInt(row["FItemID"]);
                ht_detail["mFQty"] = CommonFun.ConvertToDecimal(row["FQty"]);
                ht_detail["mFPrice"] = CommonFun.ConvertToDecimal(row["FPrice"]);
                ht_detail["mFAmount"] = CommonFun.ConvertToDecimal(row["FQty"])* CommonFun.ConvertToDecimal(row["FPrice"]);
                ht_detail["mFRemark"] = "";
                arrayList.Add(ht_detail);
            }
            ht_master["goods_list"] = arrayList;
            try
            {
                //string url = MiniMngCommon.YunShopUrl + "/Delivery/SaveBillData_RGoods";
                string url = SystemInfo.GetClusterHostUrl(shop_appid) + "/Delivery/SaveBillData_RGoods";

                string param = "mdatajson={0}";
                string mjson = CommonFun.GetValidJson(PluSoft.Utils.JSON.Encode(ht_master));
                param = string.Format(param, mjson, shop_appid);
                string result = MniMngService.HttpPostData(url, param);
                Hashtable ht_reust = (Hashtable)PluSoft.Utils.JSON.Decode(result);
                msg = CommonFun.ConvertToString(ht_reust["Status"]);
                if (CommonFun.ConvertToInt(ht_reust["id"]) > 0)
                {
                    mResult = 1;
                    return ht_reust;
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return null;
        }

        public static ArrayList GetOrderDetail(Int64 sBillID,string connstr)
        {
            string msql = @"SELECT g.FItemID, g.FName, g.FCode, g.FSpec, g.FUnitName, a.mFQty, a.mFPrice, a.mFAmount, d.FGoodImg
                            FROM dbo.y_Pra_Detail AS a with(NOLOCK) INNER JOIN
	                            dbo.t_Goods AS g with(NOLOCK) ON a.mFGoodID = g.FItemID INNER JOIN
	                            dbo.t_GoodsDetail AS d with(NOLOCK) ON g.FItemID = d.FItemID
                            where a.mFInterID = @mBillID";
            SqlParameterList par_list1 = new SqlParameterList();
            par_list1.Add("@mBillID", SqlDbType.Int, sBillID);
            ArrayList list_detail = DBHelper.Select(msql, par_list1.Get_List(),connstr);
            return list_detail;
        }

        /// <summary>
        /// 订单列表
        /// </summary>
        public static ArrayList GetOrderList(string shop_appid, string name, int page_index, int page_size,
            string star_date, string end_date, int state_type,out int page_count)
        {
            page_count = 0;
            int mCorpID = SystemInfo.GetSystemAppID(shop_appid, SystemAppID.CorpID);
            Int64 mStockID = SystemInfo.GetSystemAppID(shop_appid, SystemAppID.StockID);
            string connstr = SystemInfo.GetClusterConn(shop_appid);
            string msql = @"EXEC pr_Rpt_GetBllList_Require @mPageSize,@mPageIndex,@mDate1,"
                    + "@mDate2,@mCorpID,@mCheckFlag,@mStockID,@mObjectID,@mBillNo,@mDataType";
            SqlParameterList par_list = new SqlParameterList();
            par_list.Add("@mPageSize", SqlDbType.Int, page_size);
            par_list.Add("@mPageIndex", SqlDbType.Int, page_index);
            par_list.Add("@mDate1", SqlDbType.VarChar, CommonFun.ConvertToDate(star_date));
            par_list.Add("@mDate2", SqlDbType.VarChar, CommonFun.ConvertToDate(end_date));
            par_list.Add("@mObjectID", SqlDbType.Int, 0);
            par_list.Add("@mCheckFlag", SqlDbType.Int, 0);
            par_list.Add("@mDataType", SqlDbType.Int, state_type);
            par_list.Add("@mStockID", SqlDbType.Int, mStockID);
            par_list.Add("@mCorpID", SqlDbType.BigInt, mCorpID);
            par_list.Add("@mBillNo", SqlDbType.VarChar, name);
            ArrayList datalist = DBHelper.Select(msql, par_list.Get_List(), connstr);
            if (datalist != null && datalist.Count > 0)
            {
                ArrayList list_result = new ArrayList();
                foreach (Hashtable row in datalist)
                {                    
                    row["detail"] = GetOrderDetail(CommonFun.ConvertToBigInt(row["KInterID"]), connstr);
                    list_result.Add(row);
                }

                Hashtable ht = datalist[0] as Hashtable;
                page_count = Utils.GetPageCount(CommonFun.ConvertToInt(ht["FRowCount"]), page_size);
            }
            return datalist;
        }
    }    
}
